<template>
  <!-- 选择视频 -->
  <div>
    <el-button style="margin-right: 10px;" @click="detect" type="success">检测</el-button>
    <el-button type="primary" style="margin-right: 10px;" @click="track">跟踪</el-button>
    <el-select v-model="currentVideo.name" placeholder="选择视频" style="width: 200px; margin-right: 10px;"
      @click="updateVideoList">
      <el-option v-for="item in videoList" :key="item" :label="item" :value="item" @click="selectVideo(item)" />
    </el-select>
    <!-- 选择模型 -->
    <el-select v-model="currentModel" placeholder="选择模型" size="medium" style="width: 240px; margin-right: 10px;">
      <el-option v-for="item in model_info" :key="item.name" :label="item.name" :value="item.name"
        :title="item.message" />
    </el-select>
    <el-button style="margin-right: 10px;" @click="saveResult" type="primary">保存结果</el-button>
  </div>
  <!-- 展示界面 -->
  <div class="video-container">
    <div class="video-item">
      <h3>当前视频</h3>
      <video class='detect-video' :src="currentVideo.url" controls type="video/mp4" />
    </div>
    <div class="video-item">
      <h3>检测结果</h3>
      <video class='detected-video' :src="currentVideo.detected_url" controls type="video/mp4" />
    </div>
  </div>
  <!-- 轨迹展示 -->
  <div class="trajectory-container" style="margin-top: 20px;">
    <div class="trajectory-item">
      <h3>轨迹视频</h3>
      <video class='trajectory-video' :src="currentVideo.tracked_url" controls type="video/mp4" />
    </div>
    <div class="trajectory-item">
      <h3>轨迹图</h3>
      <svg ref="trackSvg" width="100%" height="100%"></svg>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { videoList, currentVideo, trajectoryChart, trackSvg } from '@/components/handleTrack'
import { SERVER_URL, model_info } from '@/components/handleApp'
import axios from 'axios'
import { TrajectoryChart } from '@/components/trajectoryChart'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

const route = useRoute()
const currentModel = ref('')  // 当前选择的模型
const usingModel = ref('')    // 当前使用的模型，检测和跟踪后更新为选择的模型

watch(currentModel, (newVal) => {
  currentVideo.value.detected_url = ''
  currentVideo.value.tracked_url = ''
  trajectoryChart.value!.initChart([], null)
})

/**
 * 保存结果
 */
function saveResult() {
  let option = ''
  if (currentVideo.value.detected_url !== '' && currentVideo.value.tracked_url !== '') {
    option = 'all'
  }
  else if (currentVideo.value.detected_url !== '') {
    option = 'detect'
  }
  else if (currentVideo.value.tracked_url !== '') {
    option = 'track'
  }
  else {
    ElMessage({
      message: '请先检测或跟踪视频',
      type: 'error',
    })
    return
  }
  axios.post(`${SERVER_URL}/track/save-video/`, {
    video_name: currentVideo.value.name,
    save_option: option,
    model_name: usingModel.value
  })
    .then((res: any) => {
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
    })
    .catch((err: any) => {
      console.error(err)
    })
}

/**
 * 更新视频列表
 */
function updateVideoList() {
  axios.get(`${SERVER_URL}/track/get-all-videos/`)
    .then((response: any) => {
      const data = response.data
      videoList.value = []
      for (const item of data) {
        videoList.value.push(item.video_name)
      }
    })
    .catch((error: any) => {
      console.error(error)
    })
}

/**
 * 选择视频
 */
function selectVideo(item: string) {
  axios.get(`${SERVER_URL}/track/get-one-video/`, {
    params: {
      video_name: item
    },
    responseType: 'blob'
  })
    .then((response: any) => {
      const url = URL.createObjectURL(response.data)
      if (currentVideo.value.url !== url) {
        currentVideo.value.detected_url = ''
        currentVideo.value.tracked_url = ''
        trajectoryChart.value!.initChart([], null)
      }
      currentVideo.value.url = url
    })
    .catch((error: any) => {
      console.error(error)
    })
}

/**
 * 检测视频
 */
function detect() {
  if (currentModel.value === '') {
    ElMessage({
      message: '请先选择模型',
      type: 'error',
    })
    return
  }
  axios.get(`${SERVER_URL}/track/start-detect/`, {
    responseType: 'blob',
    params: {
      video_name: currentVideo.value.name,
      model_name: currentModel.value
    }
  })
    .then((response: any) => {
      const url = URL.createObjectURL(response.data)
      currentVideo.value.detected_url = url
      usingModel.value = currentModel.value
    })
    .catch((error: any) => {
      console.error(error)
    })
}

/**
 * 跟踪视频中的目标并绘制轨迹
 */
async function track() {
  if (currentModel.value === '') {
    ElMessage({
      message: '请先选择模型',
      type: 'error',
    })
    return
  }
  try {
    let response = await axios.get(`${SERVER_URL}/track/start-track/`, {
      params: {
        video_name: currentVideo.value.name,
        model_name: currentModel.value
      }
    })
    console.log(response.data)
    if (trajectoryChart.value == undefined) {
      return
    }
    const trajectory_data = response.data.tracked_data.trajectory_data
    const video_data = response.data.tracked_data.video_data
    // 更新检测模型
    usingModel.value = currentModel.value
    // 更新轨迹图
    trajectoryChart.value.initChart(trajectory_data, video_data)
    trajectoryChart.value.render()

    response = await axios.get(`${SERVER_URL}/track/get-tracked-video/`, {
      params: {
        video_name: currentVideo.value.name
      },
      responseType: 'blob'
    })
    currentVideo.value.tracked_url = URL.createObjectURL(response.data)
  }
  catch (error: any) {
    console.error(error)
  }
}

/**
 * 挂载函数
 */
onMounted(() => {
  updateVideoList()
  if (trackSvg.value) {
    trajectoryChart.value = new TrajectoryChart(trackSvg.value)
    trajectoryChart.value.initChart([], null)
  }

  const video_name = route.query.video_name
  if (video_name) {
    currentVideo.value.name = video_name as string
    selectVideo(video_name as string)
  }
})
</script>

<style scoped>
.video-container {
  display: flex;
  /* 使用flexbox布局 */
  gap: 20px;
}

.video-item {
  display: flex;
  flex-direction: column;
  /* 使标签和视频垂直排列 */
  align-items: center;
}

.detect-video,
.detected-video {
  margin-top: 10px;
  width: 500px;
  height: auto;
}

.trajectory-container {
  width: 100%;
  height: 100%;
  display: flex;
  /* 使用flexbox布局 */
  gap: 20px;
}

.trajectory-item {
  display: flex;
  flex-direction: column;
  /* 使标签和视频垂直排列 */
  align-items: center;
}

.trajectory-video {
  width: 500px;
  height: auto;
}
</style>
